package com.ybkj.daijia.server.controller;

import com.ybkj.daijia.serverUtils.FilterStrUtil;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.HtmlHelper;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.server.event.model.OperationLogEvent;
import com.ybkj.daijia.server.model.Notice;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.NoticeService;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Shine
 */
@Controller
@RequestMapping(value = "notice")
public class NoticeController {

    @Autowired
    private NoticeService noticeService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;


    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView list() {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("notice")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("notice/list");

            mv.addObject("page", noticeService.queryAll());

            return mv;
        } else {
            throw new NoPermissionException();
        }


    }

    @RequestMapping(value = "view/{id}", method = RequestMethod.GET)
    public ModelAndView view(@PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("notice")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("notice/edit");

            mv.addObject("notice", noticeService.findOne(id));

            return mv;
        } else {
            throw new NoPermissionException();
        }


    }

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public ModelAndView add() {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("driversms") || subject.isPermitted("driverappnotice")) {
            ModelAndView mv = new ModelAndView();

            if (principal.isCompanyType()) {
                mv.addObject("companys", companyService.findAll());
            }

            mv.setViewName("notice/add");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    public @ResponseBody
    Result<Notice> create(
        @RequestParam(required = true, value = "content") String content,
        @RequestParam(required = true, value = "contentMore") String contentMore,
        @RequestParam(required = false, value = "name") String name,
        @RequestParam(required = false, value = "phone") String phone,
        @RequestParam(required = false, value = "username") String username,
        @RequestParam(required = false, value = "virtual") BigDecimal virtual,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime,
        @RequestParam(required = false, value = "companyId") Long[] companyId,
        @RequestParam(required = false, value = "status") Integer[] status,
        @RequestParam(required = false, value = "freeze") Boolean freeze,
        @RequestParam(required = false, value = "type") String[] type,
        @RequestParam(required = false, value = "jobType") String[] jobType,
        @RequestParam(required = true, value = "sendType") String[] sendType) {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        Setting setting = settingUtils.get();

        Result<Notice> result = new Result<Notice>();

        if (subject.isPermitted("driversms") || subject.isPermitted("driverappnotice")) {

            if (companyId != null && companyId.length == 0) {
                companyId = null;
            }
            if (status != null && status.length == 0) {
                status = null;
            }
            if (type != null && type.length == 0) {
                type = null;
            }
            if (jobType != null && jobType.length == 0) {
                jobType = null;
            }

            String sendTypes = "";
            for (String st : sendType) {
                sendTypes += st + ",";
            }

            //判断是否有过滤字段
            String filterStr = setting.getFilterStr();
            if (StringUtils.isNotBlank(filterStr)) {
                String content1 = content;
                String content2 = null;
                if (StringUtils.isNotBlank(contentMore)) {
                    content2 = HtmlHelper.html2Text(contentMore);
                }
                if (StringUtils.isNotBlank(content1)) {
                    boolean c1 = FilterStrUtil.check(content1, filterStr);
                    if (!c1) {
                        result.setSuccess(false);
                        result.setMessage("发布内容含有违规信息。");
                        return result;
                    }
                }
                if (StringUtils.isNotBlank(content2)) {
                    boolean c2 = FilterStrUtil.check(content2, filterStr);
                    if (!c2) {
                        result.setSuccess(false);
                        result.setMessage("发布内容含有违规信息。");
                        return result;
                    }
                }
            }

            noticeService
                .create(content, contentMore, name, phone, username, virtual, startTime, endTime,
                    companyId, status, freeze, type, jobType, sendTypes);

            String detail = "【%s】新增了服务人员通知【" + content + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            result.setSuccess(true);
            return result;
        } else {
            result.setSuccess(false);
            result.setMessage("您没有该权限");
            return result;
        }

    }

    @RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("notice")) {
            ModelAndView mv = new ModelAndView();

            Notice notice = noticeService.findOne(id);

            mv.addObject("notice", notice);

            mv.setViewName("notice/edit");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String update(Notice notice) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("notice")) {

            Notice db = noticeService.findOne(notice.getId());
            db.setContent(notice.getContent());

            noticeService.update(db);

            String detail = "【%s】修改了服务人员通知【" + db.getContent() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            return "redirect:list";
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public @ResponseBody
    Result<Integer> delete(Long id, HttpServletRequest req) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("noticedelete")) {
            Result<Integer> result = new Result<Integer>();

            if (null != id) {
                Notice notice = noticeService.findOne(id);
                if (null != notice) {

                    String detail = "【%s】删除了服务人员通知【" + notice.getContent() + "】";

                    noticeService.delete(notice);

                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);

                    result.setSuccess(true);
                    result.setMessage("删除成功");
                } else {
                    result.setMessage("没有可以删除的数据");
                }
            } else {
                result.setMessage("没有可以删除的数据");
            }

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @org.springframework.web.bind.annotation.InitBinder
    public void InitBinder(WebDataBinder dataBinder) {

        SimpleDateFormat dateFormat = com.ybkj.daijia.constant.DateConstant.DATE_TIME;
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

    }
}

